package components.custom
{
	import flash.events.MouseEvent;
	
	import mx.collections.IList;
	import mx.core.ClassFactory;
	
	import components.base.BaseComboBox;
	
	public class MultiSelectComboBox extends BaseComboBox
	{
		public function MultiSelectComboBox()
		{
			super();
			super.itemRenderer = new ClassFactory(CheckBoxItemRenderer);
		}
		
		private function get currentSelectedItemsName():String
		{
			var nameStr:String = "";
			for each(var i:int in selectedIndices){
				var obj:Object = dataProvider.getItemAt(i);
				if(labelField && obj.hasOwnProperty(labelField))
					nameStr += obj[labelField];
				else
					nameStr += String(obj);
				nameStr += ",";
			}
			return nameStr.slice(0, nameStr.length - 1);
		}
		
		override public function dispose():void
		{
		}
		
		override public function set dataProvider(value:IList):void
		{
			super.dataProvider = value;
			if(value != null && value.length > 0){
				var _selectedIndics:Vector.<int> = new Vector.<int>();
				for(var i:int = 0;i < value.length;i++){
					var obj:Object = value.getItemAt(i);
					if(obj.hasOwnProperty("checked") && obj.checked)
						_selectedIndics.push(i);
				}
				if(_selectedIndics.length > 0)
					super.selectedIndices = _selectedIndics;
			}
		}
		
		override protected function item_mouseDownHandler(event:MouseEvent):void
		{
			var item:CheckBoxItemRenderer = event.target as CheckBoxItemRenderer;
			if(!item)return;
			var index:int = dataProvider.getItemIndex(item.data);
			var popIndex:int = selectedIndices.indexOf(index);
			if(popIndex < 0){
				selectedIndices.push(index);
			}else{
				selectedIndices.splice(popIndex, 1);
			}
			textInput.text = currentSelectedItemsName;
		}
	}
}